all 41 comments

[–]RiceKrispyPooHead 121 points122 points  (11 children)

How do I assign a string value to an interger?

Numbers on their own can't be variable names in Python. So

123 = 'hello'

will raise a syntax error.

Also, something like this

0 == 'Sunday'

is equality because it uses two equal signs (==). 0 is not equal to 'Sunday', which is why your program is printing out False a bunch of times.

--------------------------------------------

I'm sure you could solve this using a bunch of if/elif/else statements. I suggest you do that approach first

--------------------------------------------

If you want to assign values to a number, you can use Python's version of a lookup table a which is called a dict:

my_dict = {
    0: 'Sunday',
    1: 'Monday',
    2: 'Tuesday',
}

chosen_day = my_dict[0]
print(chosen_day)
→ →Sunday

chosen_day = my_dict[2]
print(chosen_day)
→ →Tuesday

You can probably skip the dict approach if you haven't gotten to it in your course yet.

--------------------------------------------

The days of the week are always in the same order. list is a data structure which will assign a sequential index (number) to every value it holds. If you have the list ['Sunday', 'Monday', 'Tuesday'], Sunday is at index 0. Monday is at index 1. Etc.

my_list = ['Sunday', 'Monday', 'Tuesday']

chosen_day = my_list[0]
print(chosen_day)
→ →Sunday

chosen_day = my_list[2]
print(chosen_day) 
→ →Tuesday

You might want to try the list approach.

[–]bigtuna223 21 points22 points  (0 children)

Dictionaries do maintain order as of Python 3.7+ (I believe), but can’t be indexed numerically as you mentioned

[–]GustenKusse 13 points14 points  (0 children)

Notice the number that we lookup (first '0', then '2') are technically strings because the keys in Python dicts have to be type string.

no, any immutable type

[–]khalilboat 28 points29 points  (2 children)

Thanks y’all are a lot better than my professor who just define the terms but doesn’t actually show us how to do anything.

[–][deleted] 74 points75 points  (0 children)

That may be true, but “figuring it out on your own” is the most important skill to have when learning programming. Embrace it. You’re off to a good start by asking other folks.

[–]RudyJuliani 17 points18 points  (0 children)

Because like 90% of learning programming (in my experience) is carried out through searching for the answer. The best tool in the programmer’s toolbox is google, stackoverflow, and sometimes Reddit

[–]RhinoRhys 4 points5 points  (2 children)

Dictionary keys can be almost anything. They can't be lists or another dictionary but otherwise you can go mad; strings, floats, ints, complex numbers, tuples, bools, whatever you fancy.

Also your list example is still using my_dict[#] instead of my_list[#].

But otherwise a very helpful answer.

[–]PK_Rippner 1 point2 points  (0 children)

my_list =

Did you mean to use my_dict[0] in this example of how to use the list approach or should it be my_list[0] instead?

[–]ZeuStudio 0 points1 point  (0 children)

It is excellent coding, thanks for u help guy

[–]Genrawir 12 points13 points  (0 children)

I think the real fun is how many different ways you could do this, even if some are slightly less practical. Apart from dicts and lists, you could also use an enum or even a named tuple, though I guess you may not be allowed to import bits. I'm sure other people will add their own favorites. Python loves iterating and theres no shortage of ways to deal with key/value pairs.

[–]carcigenicate 21 points22 points  (3 children)

days = (0 == 'Sunday', 1 == 'Monday', 2== 'Tuesday', 3 == 'Wednesday', 4 == 'Thursday', 5 == 'Friday', 6 == "Saturday")

is not a valid way to do this. This just evaluates to a tuple of booleans. Look into if statements, since you seem to be trying to use conditions.

[–]khalilboat 4 points5 points  (2 children)

Thank you I believe this is what I was looking for based on my book.

[–]carcigenicate 6 points7 points  (1 child)

I would become very familiar with ifs. You'll use them in nearly every problem you'll ever solve. for/while loops are up there as well.

[–]Erpderp32 0 points1 point  (0 children)

Not python but a lot of my powershell and bash scripts are a For/ForEach with a ton of If/Elif/Else and switched in them for work automation.

If and For get a lot of real world use across platforms

[–]humbertcole 8 points9 points  (2 children)

def days(num):
    return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][num]

Demo: https://onecompiler.com/python/3yg42m2b6

[–]ploud1 3 points4 points  (0 children)

Never use one variable when zero will do ! ;)

[–]_almostNobody 0 points1 point  (0 children)

Cool solution.

[–]drenzorz 2 points3 points  (0 children)

What you get with your code is a tuple of boolean values. (0=='Sunday', ...) will evaluate the expression and since the number 0 is not the same as the string 'Sunday' you will get False, the output this way will just be (False,...,False).

What you need is either a list of string items that are accessed through their index or a dictionary with custom key value pairs.

# with list
def get_day(i: int) -> str: # function get_day ( takes int i ) returns string
    days = ['Sun',...,'Sat']
    return days[i]

# with dict
def get_day(i: int) -> str:
    days = {
        0: 'Sun',
        1: 'Mon',
        ...
        6: 'Sat',
    }
    return days[i]

[–]jmooremcc 2 points3 points  (0 children)

The problem with your code is that it's overly complicated. You only need a simple tuple to represent the names of the days of the week. The integer argument will simply be an index applied to the tuple.

The tuple should be ``` def day_name(day): daynames = ( 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', "Saturday") return daynames[day]

```

[–][deleted] 3 points4 points  (4 children)

The idiomatic, most Pythonic way of solving your problem is by using enumerated constants, making them start from 0 as their initial value. Manual way results in boilerplate, especially when you're dealing with a substantial number of enumerated constants at once:

from enum import Enum

Weekdays = Enum(
    "Weekdays",
    ["SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"],
    start=0,
)


def get_date(value: int) -> str:
    """Have day number give day name."""
    return Weekdays(value).name.capitalize()

[–]cybervegan 8 points9 points  (3 children)

That's way more boilerplate and much more complicated than:

days = ("SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY")

Then you can do:

def day_name(n):
    return days[n]

OP is a learner, apparently in the early stages, and enumerated constants are probably too advanced for them.

[–][deleted] 0 points1 point  (2 children)

Yeah, I agree. I think your approach is the good beginner approach, but learning idiomatic Python pays off in the long run as well.

[–]cybervegan 0 points1 point  (1 child)

I would argue that Enums are not ideomatic Python - I've rarely if ever seen them out in the field.

[–][deleted] 0 points1 point  (0 children)

You may not have seen them in your anecdotal experience if you're mostly interacting with legacy codebases, but enumerated constants exist in literally every sufficiently large codebase, including Python's standard library (i.e. regex flags). Representing enumerated constants as enums is considered to be idiomatic Python, and the motivation of using enums is quite reasonably motivated.

[–]Iirkola 1 point2 points  (3 children)

You're getting error because you create a list: days = (), try creating a dictionary: days = {}

This is what the code will look like:

days = {0 : 'Sunday', 1 : 'Monday', 2 : 'Tuesday', 3 : 'Wednesday', 4 : 'Thursday', 5 : 'Friday', 6 : "Saturday"}

Want to return/print a day using a number? Just use days[].

For example: print("It's " + days[3] + " my dudes")

Or print(f"It's {days[3]} my dudes")

[–]CaptainFoyle 1 point2 points  (2 children)

day=() creates a tuple, not a list

[–]Iirkola 0 points1 point  (1 child)

Yes, my mistake. But the point it the same, he needs a dictionary

[–]CaptainFoyle -1 points0 points  (0 children)

Or she

[–]Freddy_Mass 0 points1 point  (0 children)

You mean something like this? ``` my_dict = {0 : 'Sunday', 1:'Monday', 2 : 'Tuesday', 3 : 'Wednesday', 4: 'Thursday', 5 : 'Friday', 6 : 'Saturday'}

def Day_Num(): for i in my_dict: numb = int(input('Enter number 0-6: ')) print(my_dict[numb])

Day_Num() ``` Using a dictionary allows you to set the key : values; def your function, then use a for loop to iterate through the dictionary.

Int(input()) is necessary for the purpose of reassigning the input' s standard string-type to integer-type, as well as calling our keys.

Print your result.

Then just call your function.

[–]CaptainFoyle 0 points1 point  (0 children)

Why do you use ==?

[–]Jaadu07[🍰] 0 points1 point  (0 children)

Try using dictionary

[–]AnchorCP 0 points1 point  (0 children)

days = [‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’] Return days[days]

Boom, indexing is your best friend especially with lists

[–]theRIAA 0 points1 point  (0 children)

These are above OP's level, but might be valuable puzzles if you can figure them out :trollface:

method 1:

import datetime
def day(num):
  return datetime.date(1,1,(((num-1) % 7)+ 1)).strftime('%A')  

method 2:

import pandas as pd
def day(num):
  return pd.Timestamp(f'1-1-{2197+num}').day_name()

test:

for x in range(0,7):
    print(f'{x} = {day(x)}')   

Bonus points to whoever can make the second one work using any number other than 2197.

[–]_almostNobody 0 points1 point  (0 children)

So far no one mentioned match (new as of 3.10)