I am new to Python and am encountering an error when I use the following:
name = input("Would you please enter your name: ")
age = int(input("Would you please enter your age: "))
year = str((2017 - age)+100)
print("Your name is " + name + "and you will turn 100 years old in the year " + year)
When I open Python 3.5.3 from the Command Prompt (Windows 10), and I copy and paste this code from my notepad, the first lines appear as:
>>>> name = input("Would you please enter your name: ")
Would you please enter your name: age = int(input("Would you please enter
your age: "))
How do I circumvent this issue? From what I've read the program is supposed to break after encountering "input."
For reference I am starting to work through problem 1 from http://www.practicepython.org/exercise/2014/01/29/01-character-input.html
In Python interactive mode lines are executed at each line break so in your example is name is assigned the value of the string 'age = int(input("Would you please enter your age: "))'.
If you want to copy the full code into the interactive prompt and have it execute only after all lines then you have to add ;\ to the end of each line before you copy the text. The ; shows the assignment has ended but the \ indicates line continuation so the code isn't executed immediately:
>>> name = input("Would you please enter your name: ") ;\
... age = int(input("Would you please enter your age: "))
Would you please enter your name: NicolausCopernicolaus
Would you please enter your age: 29
>>> name
'NicolausCopernicolaus'
>>> age
29
Related
I'm trying to write a travel itinerary program using base Python functionality. In step 1, the program should ask for primary customer (making the booking) details viz name and phone number. I've written code to also handle errors like non-alphabet name entry, errors in phone number input (ie phone number not numeric, not 10 digits etc) to keep asking for valid user input, as below, which seems to work fine:
while True:
cust_name = input("Please enter primary customer name: ")
if cust_name.isalpha():
break
else:
print("Please enter valid name")
continue
while True:
cust_phone = input("Please enter phone number: ")
if cust_phone.isnumeric() and len(cust_phone) == 10:
break
else:
print("Error! Please enter correct phone number")
continue
while True:
num_travellers = input("How many people are travelling? ")
if int(num_travellers) >= 2:
break
else:
print("Please enter at least two passengers")
continue
Output:
Please enter primary customer name: sm
Please enter phone number: 1010101010
How many people are travelling? 2
For the next step, the program should ask for details of all passenger ie name, age and phone numbers and store them. I want to implement similar checks as above but my code below simply exits the loop once the number of travellers (num_travellers, 2 in this case) condition is met, even if there are errors in input:
for i in range(int(num_travellers)):
travellers = []
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
else:
print("Please enter valid name")
continue
for j in range(int(num_travellers)):
travel_age = []
age = input("Please enter passenger age: ")
if age.isnumeric():
travel_age.append(age)
else:
print("Please enter valid age")
continue
Output:
Please enter passenger name: 23
Please enter valid name
Please enter passenger name: 34
Please enter valid name
Please enter passenger age: sm
Please enter valid age
Please enter passenger age: sk
Please enter valid age
Please enter passenger age: sk
I've tried using a while loop like mentioned in this thread but doesn't seem to work. Where am I going wrong? Thanks
You have missed while True: loop when asking for passenger data. Try something like below:
travellers = []
for i in range(int(num_travellers)):
while True:
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
break
else:
print("Please enter valid name")
continue
BTW I moved travellers variable out of the loop, otherwise it is going to be cleared on every iteration.
name = input("what is your name: ")
while name:
if name.isnumeric():
name = input("please write a valid name ")
else:
print(f"hello {name}")
break
else :
print("are you without a name?")
You can directly ask for the input and check if valid in the while statement, looping until a valid name has been entered. That whole clause can be this 3 simpler lines.
while not (name := input("what is your name: ")).isalpha():
print("please write a valid name ")
print(f"hello {name}")
Output:
$ python script.py
what is your name: Agent007
please write a valid name
what is your name: 1234
please write a valid name
what is your name: Bond
hello Bond
Python 3, functions.
There is the following exercise:
Write a function that asks the user to enter his birth year, first name and surname. Keep each of these things in a variable. The function will calculate what is the age of the user, the initials of his name and print them.
for example:
John
Doh
1989
Your initials are JD and you are 32.
Age calculation depends on what year you are doing the track,
you should use input, format etc.
the given answer is:
def user_input():
birth_year = int(input("enter your birth year:\n"))
first_name = input ("enter your first name:\n")
surname = input ("enter your surname:\n")
print ("your initials are {1}{2} and you are {0} years old". format(first_name[0], surname[0],2021-birth_year))
when I run this the terminal stays empty,
hope you could help,
thank you in advance!
Make sure to call your function, so that it gets executed:
def user_input():
birth_year = int(input("enter your birth year:\n"))
first_name = input("enter your first name:\n")
surname = input("enter your surname:\n")
print("your initials are {1}{2} and you are {0} years old".format(first_name[0], surname[0], 2021-birth_year))
# Call it here
user_input()
The terminal stays empty is because you did not call the function to execute it.
def user_input():
birth_year = int(input("Please enter your birth year: "))
surname = input("Please enter your surname: ")
first_name = input("Please enter your first name: ")
print("\n\nYour initials are {1}{0} and you are {2} years old".format(first_name[0], surname[0], 2021-birth_year))
# remember to call the function
user_input()
Small change:
You can use the DateTime module to change the year rather than the hardcoded year value.
from datetime import date
def user_input():
birth_year = int(input("Please enter your birth year: "))
surname = input("Please enter your surname: ")
first_name = input("Please enter your first name: ")
print("\n\nYour initials are {1}{0} and you are {2} years old".format(first_name[0], surname[0], date.today().year-birth_year))
# remember to call the function
user_input()
I'm trying to write a function that takes user input in the form of a string and assigns it to variable a. Then takes a user input of an integer and assigns it to the variable b. The problem is when I run my code in the windows command line and enter a string thinking I'm just assigning the variable a as a string I get this error saying that it is looking for an int for variable b.
If I set variable b to equal input("Please enter starting account balance: ") instead of input(int("Please enter starting account balance: ")) the error goes away as expected but without requiring an int I don't know how I can add a try and except statement.
def player_setup():
a = input("Please enter player name: ")
print(f"Name saved as {a}.")
b = input(int("Please enter starting account balance: "))
return Player(name = a, account = b)
from BlackJackPackage.game_support_functions import welcome
from BlackJackPackage.game_support_functions import player_setup
welcome()
while True:
#Enter Player Name, and Enter Player Starting Money
human_player = player_setup()
print(f"Welcome {human_player.name}!")
print(f"You have ${human_player.account} in your account!.")
break
I'm hoping for variable a to be a string and b to be an integer. These variables should eventually be used to initialize a class called Player that needs a name(string) and an account(integer) input. It looks like the input line for a is trying to assign it's input to both a and b causing a ValueError.
Error:
C:\Users\Username\Desktop\Udemy Python>python Blackjackgame.py
Welcome to Blackjack Basic. First you will need to enter your name and
how much money you have.
Please enter player name: David
Name saved as David.
Traceback (most recent call last):
File "Blackjackgame.py", line 9, in <module>
human_player = player_setup()
File "C:\Users\David Fitzmaurice\Desktop\Udemy
Python\BlackJackPackage\game_support_functions.py", line 15, in
player_setup
b = input(int("Please enter starting account balance: "))
ValueError: invalid literal for int() with base 10: 'Please enter starting
account balance:
In the first case, you swapped int and input keywords, so you are trying to convert the string "Please enter starting account balance: " to an integer, which leads to the error ValueError: invalid literal for int() with base 10: 'Please enter starting
account balance:
So instead of
b = input(int("Please enter starting account balance: "))
It will be as below, where you take the input and then convert it to an integer.
b = int(input("Please enter starting account balance: "))
Hence the updated code will be
def player_setup():
a = input("Please enter player name: ")
print(f"Name saved as {a}.")
#Fixed this line by swapping int and input
b = int(input("Please enter starting account balance: "))
return Player(name = a, account = b)
from BlackJackPackage.game_support_functions import welcome
from BlackJackPackage.game_support_functions import player_setup
welcome()
while True:
#Enter Player Name, and Enter Player Starting Money
human_player = player_setup()
print(f"Welcome {human_player.name}!")
print(f"You have ${human_player.account} in your account!.")
break
I started learning python and now I stuck with this "easy" code. Where is the problem, thanks in advance!
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + "! Your are " + age)
...in the console the strings (name + input) are red and while I´m typing, I can´t see what I´m typing. After I entered a name and press enter, I get this in my console:
Enter your name:Hello Bob! Your are
Enter your age:
Process finished with exit code 0